<template>
  <!-- 添加或修改菜单对话框 -->
  <el-dialog :title="!form.categoryId ? '新增' : '修改'" append-to-body :visible.sync="visible" :close-on-click-modal="false">
    <el-form ref="dataForm" :model="form" :rules="rules" label-width="80px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="上级分类">
            <treeselect v-model="form.parentId" :options="categoryOptions" :normalizer="normalizer" :show-count="true" placeholder="选择上级分类" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属店铺">
            <el-select v-model="form.shopId" placeholder="选择所属店铺">
              <el-option v-for="item in shopList" :key="item.shopId" :label="item.shopName" :value="item.shopId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="分类名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入分类名称" />
      </el-form-item>
      <el-form-item v-if="form.categoryLevel === 3" label="图标" prop="icon">
        <el-upload :headers="headers" :show-file-list="false" :on-success="handleIconSuccess" action="/admin/sys-file/upload">
          <img v-if="form.icon" id="icon" :src="form.icon" class="icon" style="width: 178px; height: 178px" />
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>
      <el-form-item v-if="form.categoryLevel === 1" label="分类显示的图片" prop="imgUrl">
        <el-upload :headers="headers" :show-file-list="false" :on-success="handleImgUrlSuccess" action="/admin/sys-file/upload">
          <img v-if="form.imgUrl" id="imgUrl" :src="form.imgUrl" class="imgUrl" style="width: 178px; height: 178px" />
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="排序" prop="sortOrder">
            <el-input-number v-model="form.sortOrder" controls-position="right" :min="0" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio-button :label="0">禁用</el-radio-button>
              <el-radio-button :label="1">开启</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="dataFormSubmit">确 定</el-button>
      <el-button @click="visible = false">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addObj, fetchTree, getObj, putObj } from "@/api/product/category";
import { list } from '@/api/product/shopDetail'
import Treeselect from "@riophae/vue-treeselect";
import TableForm from "./";
import store from "@/store";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "CategoryForm",
  components: { Treeselect, TableForm },
  data() {
    return {
      headers: {
        Authorization: "Bearer " + store.getters.access_token,
      },
      // 遮罩层
      loading: true,
      // 菜单树选项
      categoryOptions: [],
      // 是否显示弹出层
      visible: false,
      form: {
        categoryId: undefined,
        name: undefined,
        icon: undefined,
        imgUrl: undefined,
        shopId: undefined,
        categoryLevel: 1,
        status: 1,
        sortOrder: 999,
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "分类名称不能为空", trigger: "blur" },
        ],
        sortOrder: [
          { required: true, message: "分类顺序不能为空", trigger: "blur" },
        ],
      },
      shopList: [],
    };
  },
  mounted() {
    list().then(res => {
      this.shopList = res.data.data
    })
  },
  methods: {
    handleIconSuccess(res, file) {
      this.icon = URL.createObjectURL(file.raw);
      this.form.icon = res.data.url;
    },
    handleImgUrlSuccess(res, file) {
      this.imgUrl = URL.createObjectURL(file.raw);
      this.form.imgUrl = res.data.url;
    },
    init(isEdit, id, categoryLevel) {
      this.form.icon = undefined
      this.form.imgUrl = undefined
      if (id !== null) {
        this.form.parentId = id;
      }
      this.visible = true;
      this.getTreeselect();
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (isEdit) {
          getObj(id).then((response) => {
            this.form = response.data.data;
          });
        } else {
          this.form.categoryLevel = categoryLevel
          this.form.status = 1
          this.form.sortOrder = 999
          this.form.categoryId = undefined;
        }
      });
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          if (this.form.parentId === undefined) {
            this.form.parentId = 0;
          }

          if (this.form.categoryId) {
            putObj(this.form).then((data) => {
              this.$message.success("修改成功");
              this.visible = false;
              this.$emit("refreshDataList");
            });
          } else {
            addObj(this.form).then((data) => {
              this.$message.success("添加成功");
              this.visible = false;
              this.$emit("refreshDataList");
            });
          }
        }
      });
    },
    /** 查询菜单下拉树结构 */
    getTreeselect() {
      fetchTree({ name: "" }).then((response) => {
        this.categoryOptions = [];
        const category = {
          id: 0,
          name: "根部门",
          children: response.data.data,
        };
        this.categoryOptions.push(category);
      });
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }

      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
  },
};
</script>
